/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Util;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.AudioDevice;
import javazoom.jl.player.FactoryRegistry;
import javazoom.jl.player.Player;

/**
* Classe de MP3 Player para tocar sons no jogo, tocando uma música em uma thread separada.
* */
public class Musica {
    Player player;
    boolean playing;
    String filename;

    //Toca a música especificada na string filename
    public void play(final String filename) throws JavaLayerException {
        playing = true;
        this.filename = filename;
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    InputStream input = ClassLoader.getSystemResourceAsStream(filename);
                    BufferedInputStream bin = new BufferedInputStream(input);
                    AudioDevice dev = FactoryRegistry.systemRegistry().createAudioDevice();
                    player = new Player(bin, dev);
                    player.play();
                    playing = false;
                } catch (JavaLayerException ex) {
                    Logger.getLogger(Musica.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };

        t.start();
    }

    public String getFilename() {
        return filename;
    }

    public void stop() throws InterruptedException {
        if (player != null) {
            player.close();
        }
        playing = false;
        Thread.sleep(50);
    }

    public boolean isPlaying() {
        return playing;
    }
}